from __future__ import absolute_import, unicode_literals
import time
import requests
from finance_c2c import celery_app as app
from .models import GroupChatQr
from .models import Orders
from apps.user_operation.APIClient import api_client
from django.db.models import F


@app.task()
def task_kf_send_group_chat_image(openid):
    instance = GroupChatQr.objects.first()
    instance.kf_send_image(openid)


@app.task()
def czb_refund_callback(czb_order_id, **kwargs):
    order = Orders.objects.get(id=czb_order_id)
    channel = order.channel
    app_key = channel.app_key
    if kwargs.get("status") == 1:
        d = {
            "appKey": app_key,
            "orderSn": kwargs.get("orderSn"),
            "outerOrderId": kwargs.get("outerOrderId"),
            "refundAmount": kwargs.get("refundAmount"),
            "timeStamp": str(time.time()).replace(".", "")[:13],
            "refundTradeNo": kwargs.get("refundTradeNo"),
            "status": kwargs.get("status")
        }
    else:
        d = {
            "appKey": app_key,
            "orderSn": kwargs.get("orderSn"),
            "outerOrderId": kwargs.get("outerOrderId"),
            "timeStamp": str(time.time()).replace(".", "")[:13],
            "refundTradeNo": kwargs.get("refundTradeNo"),
            "status":kwargs.get("status")
        }
    sign = api_client.get_sign(d, channel.app_secret)
    d["sign"] = sign
    channel.balance = F("balance") + order.payment_czb
    channel.save()
    order.result = 2
    order.save()
    for i in range(3):
        content = requests.post(channel.callback, json=d, verify=False)
        if content == "SUCCESS":
            break
        time.sleep(5)
